/* eslint-disable strict */
/* eslint-disable no-unused-vars */
const ws = require('nodejs-websocket');

const server = ws.createServer(socket => {

  console.log('socket.io连接成功');


  socket.on('text', data => {
    console.log('received: ' + data);
    const userData = JSON.parse(data);

    talk(JSON.stringify({
      name: `${userData.name}`,
      comment: userData.comment,
    }));

    // socket.sendText();
  });

  socket.on('close', (code, reason) => {
    console.log('connection closed!');
  });
  socket.on('error', () => {
    console.log('connection error!');
  });
});


// An Array with all connected clients. It's useful for talking a message
function talk(msg) {
  server.connections.forEach(connect => {
    connect.send(msg);
  });
}

server.listen('9000', () => {
  console.log('websocket server start at ws://10.31.71.52:9000');
});
